package com.mao.wx.demo.xml;

import java.io.Writer;

import com.mao.wx.demo.constant.WxMessageConstant;
import com.mao.wx.demo.util.StringUtil;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;



/**
 * 用于XStream将java对象转换成XML时的规则
 * @author 54353
 *
 */
public class WxXppStreamDriver extends XppDriver {
	
	@Override
	public HierarchicalStreamWriter createWriter(Writer out) {
		
		return new PrettyPrintWriter(out){
			
			@Override
			public void startNode(String name, Class clazz) {
				//设置子类型的别名
				String contentTypeName=name;
				String clazzName=clazz.getName();
				if(clazzName.equals(WxMessageConstant.CLASS_IMAGE)){
					contentTypeName="Image";
				}else if(clazzName.equals(WxMessageConstant.CLASS_LOCATION)){
					contentTypeName="Location";
				}else if(clazzName.equals(WxMessageConstant.CLASS_VEDIO)){
					contentTypeName="Vedio";
				}else if(clazzName.equals(WxMessageConstant.CLASS_VOICE)){
					contentTypeName="Voice";
				}
				super.startNode(contentTypeName,clazz);
			}

			//判断是否添加CDATA端
			@Override
			protected void writeText(QuickWriter writer, String text) {
				boolean cdata=true;
				if(StringUtil.isLong(text)||StringUtil.isDouble(text)){
					cdata=false;
				}
				if(cdata){
					writer.write("<![CDATA[");
					writer.write(text);
					writer.write("]]>");
				}else{
					writer.write(text);
				}
			}
			
		};
	}
	
	
	
}
